#include "jpeg_main.h"
#include "jpeglib.h"

#include "lvgl.h"

void jpeg_main_decode(uint8_t* inbuf, unsigned long insize, uint32_t width, uint8_t * buff, uint8_t (*callback)(uint8_t*, uint32_t))
{

    struct jpeg_decompress_struct cinfo;
    /* This struct represents a JPEG error handler */
    struct jpeg_error_mgr jerr;
    /* Decode JPEG Image */
      JSAMPROW buffer[2] = {0}; /* Output row buffer */
      uint32_t row_stride = 0; /* physical row width in image buffer */

      buffer[0] = buff;

      /* Step 1: allocate and initialize JPEG decompression object */
      cinfo.err = jpeg_std_error(&jerr);

      /* Initialize the JPEG decompression object */
      jpeg_create_decompress(&cinfo);

    //  jpeg_stdio_src (&cinfo, file);
      jpeg_mem_src(&cinfo, inbuf, insize);

      /* Step 3: read image parameters with jpeg_read_header() */
      jpeg_read_header(&cinfo, TRUE);

      /* Step 4: set parameters for decompression */
      cinfo.dct_method = JDCT_FLOAT;

      /* Step 5: start decompressor */
      jpeg_start_decompress(&cinfo);

      row_stride = width * 3;
      while (cinfo.output_scanline < cinfo.output_height)
      {
        (void) jpeg_read_scanlines(&cinfo, buffer, 1);

        if (callback(buffer[0], row_stride) != 0)
        {
          break;
        }
      }

      /* Step 6: Finish decompression */
      jpeg_finish_decompress(&cinfo);

      /* Step 7: Release JPEG decompression object */
      jpeg_destroy_decompress(&cinfo);


}
